import { RouteManager } from './routeManager';
import { DataVerify } from "./dataVerify";
import { Logger } from '../../utils/logger';

export function route(config: { path: string, method: string }) {
    return (target: any, name: string, value: PropertyDescriptor) => {
        let c = RouteManager.Current.AddController(target.toString(), target);
        RouteManager.Current.AddRoute(
            {
                target: c,
                path: config.path,
                method: config.method
            },
            target[name]
        );
    }
}

export function RequestDataVerify(adapter: IVerificationAdapter) {
    return (target: any, propertyName: string, descriptor: TypedPropertyDescriptor<Function>) => {
        DataVerify.Current.AddAdapter(descriptor.value.name, adapter);
    }
}

export interface IVerificationAdapter {
    Verify<T>(data: any): T;
}

export function RequestLog() {
    return (target: any, propertyName: string, descriptor: TypedPropertyDescriptor<Function>) => {
        RequestLogManager.Current.AddRequestLogger(descriptor.value.name);
    }
}

export class RequestLogManager {
    static Current: RequestLogManager = new RequestLogManager();
    private list: string[] = [];
    private get logger(): Logger {
        return new Logger();
    };

    AddRequestLogger(controllerName: string) {
        this.list.push(controllerName);
    }

    LogRequestCtx(ctx) {
        let headerInfo = ctx.accept.headers;
        let bodyInfo = ctx.request.body;
        let methodInfo = ctx.method;
        let cookitInfo = ctx.cookies;
        for (let item of this.list) {
            if (ctx.originalUrl.indexOf(item) > -1) {
                this.logger.getLogger("access").info(item, "__headers__:" + JSON.stringify(headerInfo), "__body__:" + JSON.stringify(bodyInfo), "__method__:" + methodInfo, "__cookies__:" + cookitInfo);
            }
        }
    }
}
